package com.bangyu.monitor.core.mqtt;

import com.bangyu.monitor.core.handler.OriginalDataHandler;
import com.bangyu.monitor.core.util.InfluxOriginalDbUtil;
import com.bangyu.monitor.core.util.SpringContextUtil;
import com.bangyu.monitor.modular.system.entity.OriginalData;
import com.bangyu.monitor.modular.system.model.OriginalDataDto;
import com.bangyu.monitor.modular.system.service.OriginalDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.MDC;

import java.util.List;
import java.util.concurrent.*;

/**
 * @Auther: zhangxue
 * @Date: 19/4/12 13:31
 * @Description:
 */
@Slf4j
public class ReceiveMsgTask implements Runnable{

    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    private byte[] payLoad;
    private String deviceNo;


    public ReceiveMsgTask(byte[] payLoad,String deviceNo,Integer deviceType) {
        this.payLoad = payLoad;
        this.deviceNo = deviceNo;

    }

    @Override
    public void run() {
        //将二进制解析为原始数据
        try{
            MDC.put("device",deviceNo);
            List<OriginalDataDto> originalDatas = null;
            originalDatas = OriginalDataHandler.newDevicehandler(payLoad,deviceNo);

            if(CollectionUtils.isNotEmpty(originalDatas)){
                //原始数据入库
                List<OriginalData> os = OriginalDataDto.toModules(originalDatas);
                InfluxOriginalDbUtil.insertOriginalData(os);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MDC.remove("device");
        }

    }

    public void execute(){
        if(payLoad != null && payLoad.length>0){
            executor.execute(this);
        }
    }
}
